<?php

include_once('datos/UsuarioDAL.php');
include_once('entities/Usuario.php');

$page = $_POST['page'];
$limit = $_POST['rows'];
$sidx = $_POST['sidx'];
$sord = $_POST['sord'];

if (!$sidx)
    $sidx = 1;

$usuario = new UsuarioDAL();

if ($_POST["_search"] == "false") {
    $lista = $usuario->obtenerUsuariosHabilitados();
} else {
    $operations = array(
        'eq' => "= '%s'",            // Equal
        'ne' => "<> '%s'",           // Not equal
        'lt' => "< '%s'",            // Less than
        'le' => "<= '%s'",           // Less than or equal
        'gt' => "> '%s'",            // Greater than
        'ge' => ">= '%s'",           // Greater or equal
        'bw' => "like '%s%%'",       // Begins With
        'bn' => "not like '%s%%'",   // Does not begin with
        'in' => "in ('%s')",         // In
        'ni' => "not in ('%s')",     // Not in
        'ew' => "like '%%%s'",       // Ends with
        'en' => "not like '%%%s'",   // Does not end with
        'cn' => "like '%%%s%%'",     // Contains
        'nc' => "not like '%%%s%%'", // Does not contain
        'nu' => "is null",           // Is null
        'nn' => "is not null"        // Is not null
    ); 
    $value = $_POST["searchString"];
    $field =  $_POST["searchField"];
    $where = sprintf("where isBorrado = 0 and %s ".$operations[$_POST["searchOper"]], $_POST["searchField"], $value);
    $lista = $usuario->obtenerUsuariosFiltro($where);
}

$count = count($lista);

if ($count > 0 && $limit > 0) {
    $total_pages = ceil($count / $limit);
} else {
    $total_pages = 0;
}

if ($page > $total_pages)
    $page = $total_pages;

$start = $limit * $page - $limit;

if ($start < 0)
    $start = 0;

header("Content-type: text/xml;charset=utf-8");

//http://stackoverflow.com/questions/13506633/paging-does-not-work-in-jqgrid

$strOut = "<?xml version='1.0' encoding='utf-8'?>";
$strOut .= "<rows>";
$strOut .= "<page>" . $page . "</page>";
$strOut .= "<total>" . $total_pages . "</total>";
$strOut .= "<records>" . $count . "</records>";

foreach ($lista as $value) {

    $strOut .= "<row id='" . $value->getIdUsuario() . "'>";
    $strOut .= "<cell>" . $value->getIdUsuario() . "</cell>";
    $strOut .= "<cell>" . $value->getNickName() . "</cell>";
    $strOut .= "<cell>" . $value->getNombreApellido() . "</cell>";
    $strOut .= "<cell>" . $value->getCodInterno() . "</cell>";
    $strOut .= "<cell>" . $value->getIdEmpresa() . "</cell>";
    $strOut .= "<cell>" . $value->getMail() . "</cell>";
    $strOut .= "<cell>" . $value->getIsAdmin() . "</cell>";
    $strOut .= "<cell>" . $value->getIsBorrado() . "</cell>";
    $strOut .= "<cell>" . $value->getPassword() . "</cell>";
    $strOut .= "</row>";
    
}

$strOut .= "</rows>";

echo $strOut;
?>